package czy.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 身份控制器,获取当前登陆用户身份
 */
@RestController
@RequestMapping("principal")
public class PrincipalController {

    private static final Logger logger = LoggerFactory.getLogger(PrincipalController.class);

    /**
     * 获取当前登陆的Principal,响应为
     * {
     *     "authorities": [
     *         {
     *             "authority": "ROLE_ADMIN"
     *         },
     *         {
     *             "authority": "ROLE_USER"
     *         }
     *     ],
     *     "details": null,
     *     "authenticated": true,
     *     "principal": {
     *         "password": null,
     *         "username": "张三",
     *         "authorities": [
     *             {
     *                 "authority": "ROLE_ADMIN"
     *             },
     *             {
     *                 "authority": "ROLE_USER"
     *             }
     *         ],
     *         "accountNonExpired": true,
     *         "accountNonLocked": true,
     *         "credentialsNonExpired": true,
     *         "enabled": true
     *     },
     *     "credentials": null,
     *     "name": "张三"
     * }
     * @param request
     * @return
     */
    @GetMapping()
    public Principal getInfo(HttpServletRequest request){
        /* 获取到的对象为UsernamePasswordAuthenticationToken实例 */
        Principal principal = request.getUserPrincipal();
        logger.info("获取用户为:"+principal.toString());
        return principal;
    }

    /**
     * 获取Authentiaction,与上面获取的是同样的东西
     * Authentication可以直接注入Controller处理方法中,如果不存在登陆用户则为null
     * @param authentication
     * @return
     */
    @GetMapping("authentication")
    public Authentication getAuthentication(Authentication authentication){
        logger.info("获取Authentication:"+authentication.toString());
        return authentication;
    }

    /**
     * 好像不能直接注入UserDetails
     * @return
     */
    @GetMapping("details")
    public UserDetails getUserDetails(Authentication authentication){
        UserDetails details = (UserDetails) authentication.getDetails();
        logger.info("获取details:"+details.toString());
        return details;
    }

    /**
     * 获取用户名
     * @param request
     * @return
     */
    @GetMapping("/remote/user")
    public String getRemoteUser(HttpServletRequest request){
        String user = request.getRemoteUser();
        logger.info("获取远程用户为:"+user);
        return user;
    }
}
